package com.zaofan.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;

import com.zaofan.bean.CarrierArea;
import com.zaofan.dao.CarrierAreaDao;
import com.zaofan.utils.C3p0DataSourceUtils;

public class CarrierAreaService {

	private CarrierAreaDao carrierAreaDao = new CarrierAreaDao();

	public void add(CarrierArea carrierArea) {
		carrierAreaDao.add(carrierArea);
	}

	public void del(CarrierArea carrierArea) {
		carrierAreaDao.del(carrierArea);
	}

	public void delByAreaId(int areaId) {
		try {
			String sql = "delete from carrierarea where areaId = " + areaId;
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(
					C3p0DataSourceUtils.getDataSource());
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void delByCarrierId(int carrierId) {
		try {
			String sql = "delete from carrierarea where carrierId = "
					+ carrierId;
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(
					C3p0DataSourceUtils.getDataSource());
			runner.update(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public List<CarrierArea> findByCarrierId(int carrierId) {
		Map<String, Object> params = new HashMap<>();
		params.put("carrierId", carrierId + "");
		List<CarrierArea> data = carrierAreaDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public CarrierArea findByAreaId(int areaId) {
		Map<String, Object> params = new HashMap<>();
		params.put("areaId", areaId + "");
		CarrierArea data = carrierAreaDao.findOne(params);

		return data;
	}

	public String findByCarrierIdAreaToIds(int carrierId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("carrierId", carrierId + "");
		List<CarrierArea> areaIds = carrierAreaDao.findAll(params);
		if (areaIds == null || areaIds.size() == 0) {
			return "";
		}
		String ids = "";
		for (CarrierArea area : areaIds) {
			ids += area.getAreaId() + ",";
		}
		if(!"".equals(ids)){
			ids = ids.substring(0, ids.length() - 1);
		}
		return ids;
	}

	public Long count(Map<String, Object> params) {
		return carrierAreaDao.count(params);
	}

	public CarrierArea findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return carrierAreaDao.findOne(params);
	}

}
